package com.southwind.filter;

import com.southwind.entity.User;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.WebFault;
import java.io.IOException;

@Component  //该注解是将写的代码交给IOC容器去管理
@WebFilter(urlPatterns = {"/index.html"},filterName ="userFilter")  //拦截 index.HTML请求
public class UserFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        向下转型 只有 继承关系的两个类才能强制转化
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        HttpSession httpSession=request.getSession();
        User user = (User)httpSession.getAttribute("User");
        if (user==null){
//            重定向到登录页面
            response.sendRedirect("/login.html");
        }else{
//            如果存在 则请求继续向后走
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
